package com.cachopoid.activity;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import ws.ServicioWeb;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.cachopoid.R;
import com.cachopoid.utils.Constantes;
import com.cachopoid.utils.MarcadorCachopo;
import com.cachopoid.vo.MarcadorVO;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapaActivity extends MapActivity implements LocationListener{

	// Atributo que representa la vista del mapa
	private MapView mapa;
	// Atributo que representa el controlador del mapa
	private MapController controlador;
	//Para realizar la b�squeda
	private Geocoder geoCoder;
	ImageView tab = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mapa);
		
        //Obtenemos una referencia al control MapView
        mapa = (MapView)findViewById(R.id.mapa);
        
        Bundle bundle = getIntent().getExtras();
        
        
        inicializarValoresMapa();

		// Obtenemos el controlador del mapa
        controlador = mapa.getController();
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        updateLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER),bundle);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 50, this);
  
	}
	
			

    protected boolean isRouteDisplayed() {
    	return false;
    }

    
    private void inicializarValoresMapa(){
		// Configuramos la vista del mapa
    	mapa.setSatellite(false);
    	mapa.setStreetView(false);
    	mapa.setTraffic(false);
        //Mostramos los controles de zoom sobre el mapa
        mapa.setBuiltInZoomControls(true);
    }
    
  
    public boolean onCreateOptionsMenu(Menu menu) {
        //Alternativa 1
    /*    MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_mapa_menu, menu);*/
        return true;
    }
    
	public boolean onOptionsItemSelected(MenuItem item) {
	   /* switch (item.getItemId()) {
	        case R.id.buscar:
	        	mostrarOcultarBuscar();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }*/
		return false;
	}
	
	public void buscar(View view){
	/*	EditText buscador = (EditText)findViewById(R.id.busqueda);
		String lugar = buscador.getText().toString();

        try {
            List<Address> addresses =
                   geoCoder.getFromLocationName(lugar, 5);
            if (addresses.size() > 0) {
                GeoPoint p = new GeoPoint(
                        (int) (addresses.get(0).getLatitude() * 1E6),
                        (int) (addresses.get(0).getLongitude() * 1E6)
                );
                controlador.setCenter(p);
                controlador.setZoom(15);

                mostrarOcultarBuscar();

                mapa.invalidate();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/
	}
	
		private void mostrarOcultarBuscar(){
		/*	LinearLayout buscador = (LinearLayout)findViewById(R.id.panelBuscar);
	    	if(buscador.getVisibility() != View.VISIBLE){
	    		buscador.setVisibility(View.VISIBLE);
	    	}
	    	else{
	    		buscador.setVisibility(View.INVISIBLE);
	    	}
		}*/
	}



		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			
		}



		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}



		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}



		@Override
		public void onProviderDisabled(String provider) {
			Intent intent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		    startActivity(intent);
			
		}
		
		protected void updateLocation(Location location, Bundle bundle){
			
	        GeoPoint point = new GeoPoint( (int) (Double.valueOf(bundle.getString(Constantes.LATITUD))* 1E6), (int) (Double.valueOf(bundle.getString(Constantes.LONGITUD))* 1E6));
	        controlador.animateTo(point);        
	        controlador.setZoom(18);
	        
	        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());

	        try {
	            List<Address> addresses = geoCoder.getFromLocation(
	                point.getLatitudeE6()  / 1E6, 
	                point.getLongitudeE6() / 1E6, 1);

	            String address = "";
	            if (addresses.size() > 0) {
	                for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
	                   address += addresses.get(0).getAddressLine(i) + "\n";
	            }

	            Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
	        }
	        catch (IOException e) {                
	            e.printStackTrace();
	        }           

	        
	        List<Overlay> mapOverlays = mapa.getOverlays();
	        MyOverlay marker = new MyOverlay(point);
	        mapOverlays.add(marker);  
	        mapa.invalidate();		
		}
		
		
		  class MyOverlay extends Overlay {
		    	GeoPoint point;
		    	
		    	public MyOverlay(GeoPoint point) {
		    		super();
		    		this.point = point;
		    	}
		    	
		        @Override
		        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
		            super.draw(canvas, mapView, shadow);                   
		 
		            Point scrnPoint = new Point();
		            mapView.getProjection().toPixels(this.point, scrnPoint);
		 
		            Bitmap marker = BitmapFactory.decodeResource(getResources(), R.drawable.marcador);
		            canvas.drawBitmap(marker,
		            		scrnPoint.x - marker.getWidth() / 2,
		            		scrnPoint.y - marker.getHeight() / 2, null);
		            return true;
		        }
		    }	
}
		
